package com.base.invoke.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 图片工具类
 * @author coolpig
 * @date 2019-09-30
 */
public class ImageUtil {

    /**
     * 画图
     */
    public static BufferedImage drawImage() {
        //得到图片缓冲区
        //INT精确度达到一定,RGB三原色，高度70,宽度150
        BufferedImage bufferedImage = new BufferedImage(150,70,BufferedImage.TYPE_INT_RGB);
        //得到它的绘制环境(这张图片的笔)
        Graphics2D g2 = (Graphics2D) bufferedImage.getGraphics();
        //填充一个矩形 左上角坐标(0,0),宽70,高150;填充整张图片
        g2.fillRect(0,0,150,70);
        //设置颜色
        g2.setColor(Color.RED);
        //填充整张图片(其实就是设置背景颜色)
        g2.fillRect(0,0,150,70);
        g2.setColor(Color.RED);
        //画边框
        g2.drawRect(0,0,150-1,70-1);
        //设置字体:字体、字号、大小
        g2.setFont(new Font("体",Font.BOLD,18));
        //设置背景颜色
        g2.setColor(Color.BLACK);
        //向图片上写字符串
        g2.drawString("HelloWorld",3,50);
        return bufferedImage;
    }

    /**
     * 这是自己写的，将bufferedImage转为base64编码值
     * 适用于这种场景： 后端在内存生成图片，然后把图片转为base64编码值，返回给前端，前端进行解码，展示图片
     * 为什么不返回流？ 如果后端返回流到前端，浏览器监控到流的返回会开启下载功能
     */
    public static String convertBufferedImageToBase64(BufferedImage bufferedImage) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        String result = null;
        try {
            ImageIO.write(bufferedImage, "jpg", bos);
            BASE64Encoder encoder = new BASE64Encoder();
            result = encoder.encode(bos.toByteArray());
        } catch (IOException e) {
            throw new IOException(e);
        } finally {
            bos.close();
        }
        return result;
    }

    /**
     * 将本地图片转换成base64字符串
     * @param imgFile	图片本地路径
     */
    public static String convertLocalImageToBase64(String imgFile) throws IOException {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        String result = null;
        try {
            // 读取图片字节数组
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            // 返回Base64编码过的字节数组字符串
            result = encoder.encode(data);
        } catch (IOException e) {
            throw new IOException(e);
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return result;
    }

    /**
     * 将网络图片转换成base64字符串
     * @param imgURL	图片线上路径
     */
    public static String convertWebImageToBase64(String imgURL) throws IOException {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        String result = null;
        InputStream is = null;
        try {
            // 创建URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            is = conn.getInputStream();
            // 将内容读取内存中
            int len;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            result = encoder.encode(data.toByteArray());
        } catch (IOException e) {
            throw new IOException(e);
        } finally {
            // 关闭流
            if (is != null) {
                is.close();
            }
        }
        return result;
    }

    /**
     * 将base64字符串转换成图片并保存到本地
     * @param imgStr		base64字符串
     * @param imgFilePath	图片存放路径
     */
    public static void convertBase64ToImageAndSaveToLocal(String imgStr,String imgFilePath) throws IOException {
        // 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null || "".equals(imgStr)) {
            return;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
        } catch (IOException e) {
            throw new IOException(e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 将bufferedImage保存到本地
     * @param savePath 保存图片的路径，细致到图片文件名
     */
    public static void saveBufferedImageToLocal(BufferedImage bufferedImage, String savePath) throws IOException {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(savePath);
            ImageIO.write(bufferedImage,"JPG",fos);
        } catch (IOException e) {
            throw new IOException(e);
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        //得到图片缓冲区
        //INT精确度达到一定,RGB三原色，高度70,宽度150
        BufferedImage bi = new BufferedImage(150,70,BufferedImage.TYPE_INT_RGB);
        //得到它的绘制环境(这张图片的笔)
        Graphics2D g2 = (Graphics2D) bi.getGraphics();
        //填充一个矩形 左上角坐标(0,0),宽70,高150;填充整张图片
        g2.fillRect(0,0,150,70);
        //设置颜色
        g2.setColor(Color.RED);
        //填充整张图片(其实就是设置背景颜色)
        g2.fillRect(0,0,150,70);
        g2.setColor(Color.RED);
        //画边框
        g2.drawRect(0,0,150-1,70-1);
        //设置字体:字体、字号、大小
        g2.setFont(new Font("体",Font.BOLD,18));
        //设置背景颜色
        g2.setColor(Color.BLACK);
        //向图片上写字符串
        g2.drawString("HelloChina",3,50);
        //保存图片 JPEG表示保存格式
        ImageIO.write(bi,"JPG",new FileOutputStream("D:\\image-test.jpg"));
    }
}
